#!/usr/bin/python

import protocol1
import sys
import subprocess
import re
import os
import tempfile

handles = []

class dhds:
	
	def __init__(self,acc1,acc2):
		
		self.acc1 = str(acc1)
		self.acc2 = str(acc2)
		self.accs =[str(acc1), str(acc2)]
		self.proceed = True
		self.fastas = []
		self.filtered_fastas = []
		
		# Some defaults
		self.e_threshold = 0.005
		self.maketable_cutoff = 0.7
		self.min_tms = 0
		self.max_gsat = 10
		self.host = "saierlab@132.239.144.24"
		
		# Run protocols
		self.protocol()
		self.runtime()
		self.run_hmmtop()
		self.tms_filter()
		self.protocol2()
		
	def protocol(self):
		if self.skip() is True:
			return
		status1 = protocol1.protocol1(self.acc1,self.e_threshold,self.maketable_cutoff)
		status2 = protocol1.protocol1(self.acc2,self.e_threshold,self.maketable_cutoff)
		if status1.success is False or status2.success is False and self.skip(self.acc1) is False and self.skip(self.acc2) is False :
			self.proceed = False
		self.fastas.append(status1.filepath)
		self.fastas.append(status2.filepath)
		return
		
	def runtime(self):
		if self.proceed is False:
			quit();
		return
		
	def protocol2(self):
		cmd = 'php /usr/bin/protocol2 -q 1 -s ../%s.faa -t ../%s.faa -o %s -m %i > /dev/null' %(self.acc1,self.acc2,'./'+self.acc1+'-'+self.acc2,self.max_gsat)
		handle=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
		handle.wait()
	
	def run_hmmtop(self):
		if self.skip() is True:
			return
		for i in range(len(self.accs)):
			if os.path.isfile("./"+self.accs[i]) is True:
				continue
			cmd = "hmmtop -if=%s sf=FAS -is=pseudo -pi=spred -of=/tmp/ramdisk/%s.hmmtop > /dev/null" %(self.fastas[i],self.accs[i])
			handles.append(subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE))
			for h in handles:
				try:
					h.communicate()
				except:
					pass
		return
		
	def tms_filter(self):
		if self.skip() is True:
			return
		for i in range(len(self.accs)):
			filtered_fastas=[]
			file = open(self.fastas[i])
			fasta = file.read()
			file.close()
			fasta = filter(lambda x:len(x)>0,fasta.split(">"))
			results = open("/tmp/ramdisk/"+self.accs[i]+".hmmtop")
			for hmmtop in enumerate(results):
				tms = re.search('(IN|OUT)\s+(\d{1,3})',hmmtop[1])
				if int(tms.groups()[1]) > self.min_tms:
					filtered_fastas.append(fasta[hmmtop[0]])
			if len(filtered_fastas) is 0:
				self.proceed = False
			else:
				file = open(self.accs[i]+".faa","w")
				file.write(">"+'>'.join(filtered_fastas))
				file.close()				
				
	def skip(self):
		if os.path.isfile('./'+self.acc1+'.faa') is True and os.path.isfile('./'+self.acc2+'.faa') is True:
			return True
		return False
		
	def send_compared(self):
		send = "scp -r ./%s %s:/Library/Webserver/compared" %(self.acc1+"-"+self.acc2,self.host)
		handle.subprocess.Popen(send, shell=True, stdout=subprocess.PIPE)
		handle.wait()
		return
	
	def send_acc(self,acc):
		send = "scp -r ./%s.faa %s:/Library/Webserver/" %(acc,self.host)
		handle.subprocess.Popen(send, shell=True, stdout=subprocess.PIPE)
		handle.wait()
		return
		